﻿spsetBaseNoBt("mrDepartment", "DepID", "mrDepartment as T", "*", "#ui_department_tg", "mrdep", "部门");
var Mbranchobj;//机构对象
var Mbankobj
$(function () {
    var showtype = getUrlParam("showtype");
    if (showtype == 0) {
        $("#nofindtype").combobox("select", "机构");
    }
    else if (showtype == 1) {
        $("#nofindtype").combobox("select", "银行");
    }
    else {
        $.messager.alert("提示信息", "没定义的参数！");
        return;
    }
   

    //  $('#findBranchID').combobox('setValue', '23');//这个就是需要给默认值的地方,1表示启用,与下面的值对应.

    $('#nofindtype').combobox({
        onChange: function (newValue, oldValue) {
            if (newValue == "机构") {
                $("#fBranchID").combobox("loadData", Mbranchobj);
                $("#findBranchID").combobox("loadData", Mbranchobj);

            }
            else {
                $("#fBranchID").combobox("loadData", Mbankobj);
                $("#findBranchID").combobox("loadData", Mbankobj);
            }
        }
    });
    //这里data: datebranch  无法加载数据
    var datebranch = spGetJson(sposelUrlByFNoState("BranchID,BranchName", "mrBranch", "type in('本部','分部')", "", "", "BranchID"));
    Mbranchobj = $.parseJSON(datebranch);
    datebranch = spGetJson(sposelUrlByFNoState("BranchID,BranchName", "mrBranch", "type in('银行','分行','一级支行')", "", "", "BranchID"));
    Mbankobj = $.parseJSON(datebranch);

    $('#fBranchID').combobox({
        editable: false,
        valueField: 'BranchID',
        textField: 'BranchName',
        multiple: false,
        // data: datebranch,
        onChange: function (newValue, oldValue) {
            runloadselecttree(newValue);
        },
        onLoadSuccess: function () { //加载完成后,设置选中   当前机构 第一项
            //var val = $(this).combobox("getData");
            //for (var i = 0; i < val.length; i++) {
            //    if (val[i]["BranchID"] == HCUser.HCUorg) {
            //        $(this).combobox("select", val[i]["BranchID"]);
            //        break;
            //    }
            //}

        }
    });
    $('#findBranchID').combobox({
        editable: false,
        valueField: 'BranchID',
        textField: 'BranchName',
        multiple: false,
        onChange: function (newValue, oldValue) {
            Search();
        },
        onLoadSuccess: function () {
            var val = $(this).combobox("getData");
            for (var i = 0; i < val.length; i++) {
                if (val[i]["BranchID"] == HCUser.HCUorg) {
                    $(this).combobox("select", val[i]["BranchID"]);
                    break;
                }
            }
            if (HCUser.HCUorg != 106) {
                $('#findBranchID').combobox('readonly',true);
            }
        }
    });
    if (showtype == 0) {
        $("#fBranchID").combobox("loadData", Mbranchobj);
        $("#findBranchID").combobox("loadData", Mbranchobj);
    }
    else if (showtype == 1) {
        $("#fBranchID").combobox("loadData", Mbankobj);
        $("#findBranchID").combobox("loadData", Mbankobj);
    }

    BindGrid();
});


var oldSelectDepartmentId;   //上次点选的DepartmentId

function BindGrid() {


    $(grid1ID).treegrid({       //初始化treegrid
        url: urltree,
        idField: 'id',
        treeField: 'text',
        rownumbers: true,
        toolbar:
            [
            { id: 'btnAdd', text: '新增', iconCls: 'icon-add', handler: toolAdd },
            //{ id: 'btnUpdate', text: '修改', iconCls: 'icon-edit', handler: Update },
{ id: 'btnDel', text: '删除', iconCls: 'icon-delete', handler: toolDelete },
{ id: 'btnopenall', text: '展开', iconCls: 'icon-download', handler: ui_department_expandall },
{ id: 'btnCheckPass', text: '隐藏', iconCls: 'icon-upload', handler: ui_department_collapseall }
            ],
        columns: [[
                    { field: 'text', title: '部门名称', width: 250 },
                    { field: 'ShowInfo2', title: '机构', width: 250 },
        {
            field: "y", title: "操作", width: 50, align: "center", formatter: function (value, row, index) {
                return "<a href='#' style='color: #369591;' onclick='javascript:Update(" + row.id + ")'>修改</a>";
            }
        }

        ]],
        onClickRow: function (row) {


            if (oldSelectDepartmentId == row.id) {  //点选的是相同的部门就不再请求数据
                return;
            }
            oldSelectDepartmentId = row.id;   //赋值
            var $ui_department_layout = $("#ui_department_layout");
            var eastDepartmentUser = $ui_department_layout.layout("panel", "east");

            if (eastDepartmentUser.panel("options").collapsed) {   //判断是否展开
                $ui_department_layout.layout("expand", "east");
            }
            eastDepartmentUser.panel("setTitle", row.text + "--成员");

            if ($("#ui_department_user_dg").data("datagrid")) {
                $("#ui_department_user_dg").datagrid({
                    url: sposelUrl("mrBaseInf as T ", "*", "and DepID=" + row.id)
                });
            }
            else {
                $("#ui_department_user_dg").datagrid({       //初始化datagrid
                    url: sposelUrl("mrBaseInf as T ", "*", "and DepID=" + row.id),
                    striped: true, rownumbers: true, pagination: true, pageSize: 20, singleSelect: true,
                    idField: 'EmpID',
                    // sortName: 'AddDate',
                    // sortOrder: 'asc',
                    pageList: [20, 40, 60, 80, 100],
                    columns: [[
                          { field: 'LoginID', title: '登录名', sortable: true, width: 100 },
                          { field: 'EmpName', title: '姓名', sortable: true, width: 80 }

                    ]]
                });
            }
        },
        queryParams: $("#searchForm").formToJson()
        //onBeforeLoad: function (param) {
        //    $.extend(param, $("#searchForm").formToJson());
        //}
    });



}
var departmentIds = "";
function recursionGetIds(rows) {
    if (rows.children != undefined) {
        $.each(rows.children, function (i, row) {
            //console.log(row.id + "：" + row.text);
            departmentIds += row.id + ",";
            recursionGetIds(row);   //递归
        });
    }
}
function ui_department_expandall() {
    $("#ui_department_tg").treegrid("expandAll");
}
function ui_department_collapseall() {
    $("#ui_department_tg").treegrid("collapseAll");
}
function runloadselecttree(id) {
    $('#fParentId').combotree({
        url: urltree + '&wheresp= and T.BranchID=' + id
        //onBeforeExpand: function (node) {
        //    $('#fParentId').combotree("tree").tree("options").url = urltree + '&wheresp= and T.BranchID='+id;
        //}
    });
}

var urltree = "../ashx/sp.ashx?action=seltree&tableinfo= mrDepartment as T inner join mrBranch  as T1 on T.BranchID=T1.BranchID   &refields= DepID as ID,DepName  as ShowInfo,T1.BranchName as ShowInfo2,T.ParentId";
function Search() {
    //为什么 reload不带参数过去？
    // $(grid1ID).treegrid("options").queryParams = $("#searchForm").formToJson();
    $.ajax({
        type: "POST",
        url: urltree,
        data: $("#searchForm").formToJson(),
        success: function (Data) {
            $(grid1ID).treegrid("loadData", eval(Data));
            // top.ajaxLoaded();
        }
    });
}

function Reset() {

    $("#finddename").val("");
}

function toolAdd() {
    $(grid1ID).datagrid("clearSelections");
    $('#itemEdit')[0].reset();
    $("#editAction").val(CallBackCommand.Inseart);
    $('#itemEditContainer').window({ title: "新增" + pPageInfoName + "信息" });
    $("#itemEditContainer").window("open");
    $("#fBranchID").combobox("select", HCUser.HCUorg);
    if (HCUser.HCUorg != 106) {
        $('#fBranchID').combobox('readonly', true);
    }
}

function Update(id) {

    //alert($("#fBranchID").attr("class"));
    //alert($("#fParentId").attr("class"));
    //alert($("#fDepName").attr("class"));
    //alert($("#fManager").attr("class"));

    //$("#itemEdit").validatebox("remove"); //删除  
    //$("#itemEdit").validatebox("reduce"); //恢复  
    $(".validatebox-tip").remove();
    $(".validatebox-invalid").removeClass("validatebox-invalid");
    //$(grid1ID).datagrid("selectRow", index);
    //var row = $(grid1ID).datagrid("getSelected");
    $('#itemEdit')[0].reset();
    $("#editAction").val(CallBackCommand.Update);
    // var id = row[pTableIdName];
    $("#id").val(id);

    //方法2从数据库中找出(内容不在列表时)
    {
        $.get(spselrowUrl(id),
            function (data) {
                var data = JSON.parse(data);
                if (data.message == JsonResult.Success) {
                    //$('#itemEdit').form('load', data.data);
                    for (var i = 0; i < data.data.length; i++) {
                        var infoobj = data.data[i];
                        for (var filedname in infoobj) {
                            var gethtmlf = $("#f" + filedname);
                            if (gethtmlf && gethtmlf.length == 1) {
                                if (filedname.substring(0, 2) == "dt")
                                { gethtmlf.datebox('setValue', infoobj[filedname]); }
                                else if (filedname == "BranchID") {
                                    //gethtmlf.val(infoobj[filedname]);
                                    gethtmlf.combobox('setValue', infoobj[filedname]);
                                }
                                else if (filedname == "ParentId") {
                                    gethtmlf.combotree('setValue', infoobj[filedname]);
                                }
                                else { gethtmlf.val(infoobj[filedname]); }
                            }
                        }
                        break;
                    }
                }
                else {
                    $.messager.show({
                        title: '查找出错',
                        msg: data.data,
                        showType: 'show'
                    });
                }


            });
    }


    $('#itemEditContainer').window({ title: "修改信息" });
    $("#itemEditContainer").window("open");
}

function toolDelete() {
    var rows = $(grid1ID).datagrid("getSelections");
    if (rows.length == 0) {
        $.messager.alert("提示信息", "请选择需要删除的数据！");
    } else {
        $.messager.confirm("提示信息", "确定删除所选数据？", function (r) {
            if (!r) {
                $(grid1ID).datagrid("clearSelections");
                return;
            }
            var ID = "";
            for (var i = 0; i < rows.length; i++) {
                // ID += rows[i].fid + ",";rows[i][pTableIdName]
                ID += rows[i]["id"] + ",";
            }
            ID = ID.substring(0, ID.length - 1);
            $.get(spdelUrl(ID),
            //$.post(pageUrl + "?tablename=" + pTableName + "&tablemidname" + pTableIdName, { ID: ID, action: CallBackCommand.Delete },
            function (data) {
                var data = JSON.parse(data);
                switch (data.message) {
                    case JsonResult.SessionOut:
                        $.messager.alert('系统出错', ' 登录超时，请重新登录!');
                        break;
                    case JsonResult.Error:
                        $.messager.alert('系统出错', data.data);
                        break;
                    case JsonResult.Success:
                        $.messager.show({
                            title: '提示信息',
                            msg: data.data,
                            showType: 'show'
                        });
                        $(grid1ID).datagrid("clearSelections");
                        //$(grid1ID).datagrid("clearSelections");
                        //$(grid1ID).datagrid("load");
                        //$(grid1ID).treegrid("reload");
                        Search();

                        $("#ui_department_layout").layout("collapse", "east");
                        $("#ui_department_user_dg").datagrid('loadData', { total: 0, rows: [] });   //清空
                        break;
                }
            });
        });
    }
}



function editSubmit() {
    $("#tablename").val(pTableName);
    $("#tablemidname").val(pTableIdName);
    if (!$("#itemEdit").form('validate'))
    { return; }
    $('#itemEdit').ajaxSubmit(function (message) {
        var data = JSON.parse(message);
        if (data.message == JsonResult.Success) {
            $('#itemEditContainer').window('close');
            $.messager.show({
                title: '消息',
                msg: '信息提交成功',
                showType: 'show'
            });
            //$(grid1ID).datagrid("load");
            Search();
        }
        else {
            $.messager.show({
                title: '提交出错',
                msg: data.data,
                showType: 'show'
            });
        }

    });

}

